package cn.iocoder.yudao.im.server.task;

import cn.iocoder.yudao.im.common.contant.IMRedisKey;
import cn.iocoder.yudao.im.common.enums.IMCmdType;
import cn.iocoder.yudao.im.common.model.IMRecvInfo;
import cn.iocoder.yudao.im.server.netty.IMServerGroup;
import cn.iocoder.yudao.im.server.netty.processor.AbstractMessageProcessor;
import cn.iocoder.yudao.im.server.netty.processor.ProcessorFactory;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
public class PullGroupMessageTask extends AbstractPullMessageTask {


    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void pullMessage() {
        // 从redis拉取未读消息
        String key = String.join(":", IMRedisKey.IM_MESSAGE_GROUP_QUEUE, IMServerGroup.serverId + "");
        Object o = redisTemplate.opsForList().leftPop(key);
        while (!Objects.isNull(o)) {
            String jsonString = JSON.toJSONString(o);
            IMRecvInfo recvInfo = JSON.parseObject(jsonString, IMRecvInfo.class);
            AbstractMessageProcessor processor = ProcessorFactory.createProcessor(IMCmdType.GROUP_MESSAGE);
            processor.process(recvInfo);
            // 下一条消息
            o = redisTemplate.opsForList().leftPop(key);
        }
    }

}
